package com.example.app.ui.components

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

@Composable
fun TopAppBar(modifier: Modifier=Modifier,content: @Composable () -> Unit) {
    //标题栏高度
    val appBarHeight=56.dp
    val statusBarHeight=GetStatusBarHeight()
    Row(
        horizontalArrangement = Arrangement.Center,
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .fillMaxWidth()
            .height(appBarHeight+statusBarHeight)
            .then(modifier)
            .statusBarsPadding()
    ) {
        content()
    }
}

@Composable
fun GetStatusBarHeight(): Dp {
    val view = LocalView.current
    val density = LocalDensity.current

    val statusBarHeight = remember { mutableIntStateOf(0) }

    DisposableEffect(view) {
        val insets = ViewCompat.getRootWindowInsets(view)
        if (insets != null) {
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            statusBarHeight.intValue = systemBars.top
        }

        onDispose {}
    }

    return with(density) { statusBarHeight.intValue.toDp() }
}


@Preview
@Composable
fun TopAppBarPreview() {
    TopAppBar() {
        Text(text = "标题")
    }
}